﻿

using System;
using Kevin.Comm.Utility.Crypto;
using Kevin.Shop.Business.Core.Components;
using Kevin.Shop.Business.Core.Components.Responser;
using Kevin.Shop.Business.Core.Member;
using Kevin.Shop.Business.Service.Entity.Core.Member;
using Kevin.Shop.Business.Service.Entity.Helper;
using Kevin.Shop.Business.Service.Entity.SalesManagement.XianXiangCard;
using RiderShop.Mobile.Common.Component;
using RiderShop.Mobile.Common.ThirdEntity;
using System.Collections.Generic;

namespace RiderShop.Mobile.Modle
{
    public class CustomerModel
    {
        private UserBasicInfo _currentUser;
        public ServiceResponser Result { get; set; }

        public DbQueryResult<List<XianXiangCardEntity>> XianXiangCardList { get; set; }
        public List<XianXiangCardEntity> CurrentUserXianXiangCardNumberList { get; set; }
        public int SelectedXianXiangCardNumberCount { get; set; }

        private string returnUrl;
        public string ReturnUrl
        {
            get
            {
                if (string.IsNullOrEmpty(returnUrl))
                {
                    returnUrl = WebClientContext.Current.ReturnUrl;
                }
                return returnUrl;
            }
            set { returnUrl = value; }
        }

        public string OpenId { get; set; }

        public UserBasicInfo CurrentUser
        {
            get
            {
                return _currentUser != null ? _currentUser : new UserBasicInfo();
            }
            set { _currentUser = value; }
        }

        public void Login(string userName, string password)
        {
            CurrentUser = new UserBasicInfo();
            CurrentUser.UserName = userName;
            if (!string.IsNullOrEmpty(userName))
            {
                Result = RestfulHelper.UpdateWithQueryString(SiteUrl.FormatUrl("Common_UserLogin", userName, userName, password));
            }
        }

        public void Register(UserBasicInfo user)
        {
            CurrentUser = user;
            Result = RestfulHelper.Update(SiteUrl.FormatUrl("Common_CreateOrUpdateByWebSite"), user);
        }

        public void RegisterUserByCellPhone(string cellPhone, string password, string verifyCode, string device)
        {
            if (string.IsNullOrWhiteSpace(cellPhone))
            {
                Result = new ServiceResponser(false, "请输入手机号");
                return;
            }

            if (!(new System.Text.RegularExpressions.Regex("^1\\d{10}$")).IsMatch(cellPhone))
            {
                Result = new ServiceResponser(false, "请输入正确手机号");
                return;
            }

            if (string.IsNullOrWhiteSpace(verifyCode))
            {
                Result = new ServiceResponser(false, "请输入验证码");
                return;
            }

            if (string.IsNullOrWhiteSpace(password))
            {
                Result = new ServiceResponser(false, "请输入密码");
                return;
            }

            if (password.Length < 6)
            {
                Result = new ServiceResponser(false, "请输入至少六位密码");
                return;
            }


            UserBasicInfo user = new UserBasicInfo()
            {
                CellPhone = cellPhone,
                Password = password,
                PasswordAnswer = verifyCode,
                RegisterDevice = device
            };

            CurrentUser = user;
            Result = RestfulHelper.Update(SiteUrl.FormatUrl("Common_RegisterUserByCellPhone"), user);

        }

        public void ChangePassword(string oldPwd, string newPwd)
        {
            int userId = WebClientContext.Current.UserId;
            int changeUser = userId;
            string encodeOldPwd = SystemEncrypt.Encrypt(oldPwd);
            string encodeNewPwd = SystemEncrypt.Encrypt(newPwd);
            var simpleUser = new SimpleUser()
                                 {
                                     CurrentUserId = changeUser,
                                     UserId = userId,
                                     Password = encodeOldPwd,
                                     OldPassword = encodeNewPwd
                                 };
            Result = RestfulHelper.Update(SiteUrl.FormatUrl("Common_UpdateUserPassword"), simpleUser);
        }

        public void ResetPassword(string newPwd, string forgetpwd)
        {
            int userId = WebClientContext.Current.UserId;

            string encodeNewPwd = SystemEncrypt.Encrypt(newPwd);
            var simpleUser = new SimpleUser()
            {
                PublicToken = forgetpwd,
                UserId = userId,
                Password = encodeNewPwd,
                OldPassword = encodeNewPwd
            };
            Result = RestfulHelper.Update(SiteUrl.FormatUrl("Common_UpdateUserPassword"), simpleUser);
        }

        public void BindUserInfoByWeixin(string userName, string openid)
        {
            var user = RestfulHelper.QueryWithSingle<UserBasicInfo>(SiteUrl.FormatUrl("Common_GetUserInfoByName", userName));
            user.ThirdUserId = "weixing_" + openid;
            ServiceResponser result = MyAccount.MyAccountModel.UpdateUser(user);
            WebClientContext.Current.GetCurrentUser(false);
        }

        public void BindUserInfoByWeixin(string userName, WinXinUserInfo weixinUserInfo)
        {
            var user = RestfulHelper.QueryWithSingle<UserBasicInfo>(SiteUrl.FormatUrl("Common_GetUserInfoByName", userName));
            user.ThirdUserId = "weixing_" + weixinUserInfo.openid;
            user.UnionId = weixinUserInfo.unionid;
            if (string.IsNullOrEmpty(user.RealName))
            {
                user.RealName = weixinUserInfo.nickname;
            }
            if (string.IsNullOrEmpty(user.HeadImgUrl))
            {
                user.HeadImgUrl = weixinUserInfo.headimgurl;
            }

            ServiceResponser result = MyAccount.MyAccountModel.UpdateUser(user);
            WebClientContext.Current.GetCurrentUser(false);
        }


        public void WeixinRegister(WinXinUserInfo weixinUserInfo)
        {
            var user = new UserBasicInfo();
            string username = "weixing_" + System.DateTime.Now.ToString("yyMMddhhmmssfff");
            user.ThirdUserId = "weixing_" + weixinUserInfo.openid;
            user.UserName = username;
            user.RealName = weixinUserInfo.nickname;
            user.Password = "!@#$%^&*()";
            user.Email = username + "@notset.com";
            user.MSN = "weixinfirstlogin"; //作为微信注册标记字段，用户绑定手机号设置密码后清空
            user.EnableEmail = false;
            user.HeadImgUrl = weixinUserInfo.headimgurl;
            user.UnionId = weixinUserInfo.unionid;
            string url = SiteUrl.FormatUrl("Common_CreateOrUpdateUser");
            Result = RestfulHelper.Update(url, user);

            CurrentUser = user;
        }

        #region 鲜享卡
        /// <summary>
        /// 得到鲜享卡
        /// </summary>
        /// <returns></returns>
        public void GetXianXiangCard(int type, int status)
        {
            string url = SiteUrl.FormatUrl("SalesManagement_GetXianXiangCard");
            var query = new XianXiangCardQuery()
            {
                Type = type,
                Status = status,
                UserId = -1
            };

            XianXiangCardList = RestfulHelper.Query<XianXiangCardEntity>(url, query);
        }

        /// <summary>
        /// 认购鲜享卡
        /// </summary>
        /// <returns></returns>
        public ServiceResponser SubscribeXianXiangCard(string cardNumber)
        {
            var request = new XianXiangCardEntity()
            {
                CardNumber = cardNumber,
                UserId = WebClientContext.Current.UserId
            };

            string url = SiteUrl.FormatUrl("SalesManagement_SubscribeXianXiangCard");
            var result = RestfulHelper.Update(url, request);

            return result;
        }

        /// <summary>
        /// 根据用户编号得到鲜享卡
        /// </summary>
        /// <returns></returns>
        public void GetXianXiangCardByUserId()
        {
            string url = SiteUrl.FormatUrl("SalesManagement_GetXianXiangCardByUserId", WebClientContext.Current.UserId);
            var result = RestfulHelper.Query<XianXiangCardEntity>(url);

            CurrentUserXianXiangCardNumberList = result;
        }
        #endregion
    }
}
